package com.tanx.cqrs.eventsourcing.snapshot;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

/**
 * 快照仓库
 */
@Data
public class MongoSnapshotRepositoryImpl<T> implements SnapshotRepository<T> {
    @Autowired
    private MongoTemplate mongoTemplate;
    private String collectionName;

    @Override
    public Snapshot findTop1SnapByCreateDateTimeDesc(Object id) {
        Query query = new Query(Criteria.where("_id").is(id));
        query.limit(1).with(new Sort(Sort.Direction.DESC, "createDateTime"));
        return mongoTemplate.findOne(query, MongoSnapshotImpl.class, collectionName);
    }

    @Override
    public void save(Snapshot snapshot) {
        mongoTemplate.save(snapshot, collectionName);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T getAggregate(Snapshot snapshot) {
        return (T) snapshot.toAggregate();
    }
}
